#!/usr/bin/env ruby
#
# Amarok Script for fetching song lyrics from http://www.jamendo.com
#
# (C) 2007 Harald Sitter <sitter.harald@gmail.com>
#          http://amarok.kde.org
#
# License: GNU General Public License V2

require "net/http"
require "rexml/document"
require "uri"

@scriptversion = "1.0.2"
@app_name = "Lyrics_Jamendo"

class String
    def shellquote
        return "'" + self.gsub("'", "'\\\\''") + "'"
    end
end

def fetchLyrics( artist, title, url )
    qartist = @artist.gsub(/[ ]/, '+')
    qtitle  = @title.gsub(/[ ]/, '+')
    qalbum  = @album.gsub(/[ ]/, '+')

    host = "www.jamendo.com"
    path = url.empty? ? "/en/get/track/list/track-artist-album/lyricstext/plain/?searchterm=#{qtitle}&artist_searchterm=#{qartist}&album_searchterm=#{qalbum}&tri=lyrics+lyrics_text&searchin=track&artist_searchin=artist&album_searchin=album" : "#{url}"
    @page_url = "http://" + host + path

    proxy_host = nil
    proxy_port = nil
    if ( @proxy == nil )
        @proxy = `dcop amarok script proxyForUrl #{@page_url.shellquote}"`
    end
    proxy_uri = URI.parse( @proxy )
    if ( proxy_uri.class != URI::Generic )
        proxy_host = proxy_uri.host
        proxy_port = proxy_uri.port
    end

    h = Net::HTTP.new( host, 80, proxy_host, proxy_port )
    response = h.get( path )

    unless response.code == "200"
        showLyrics( "" )
        return
    end

    lyrics = response.body()

    if lyrics != ""
        processLyrics( lyrics )
        return
    else
        notFound()
    end

    rescue SocketError
        showLyrics( "" )
end

def processLyrics( lyrics )
    doc = REXML::Document.new( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" )
    root = doc.add_element( "lyrics" )

    # refetch title and artist since Amarok transcoded to HTML entities
    @title  = `dcop amarok player title`.chomp()
    @artist = `dcop amarok player artist`.chomp()

    root.add_attribute( "page_url", @page_url )
    root.add_attribute( "title", @title )
    root.add_attribute( "artist", @artist )

    root.text = lyrics

    xml = ""
    doc.write( xml )

    showLyrics( xml )
end

def notFound()
    doc = REXML::Document.new( "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" )
    root = doc.add_element( "suggestions" )
    xml = ""
    doc.write( xml )
    showLyrics( xml )
end

def showLyrics( lyrics )
    system("dcop", "amarok", "contextbrowser", "showLyrics", lyrics)
end

########################## Start the Jamendo love :-D ##########################

loop do
    message = gets().chomp()
    command = /[A-Za-z]*/.match( message ).to_s()

    case command
        when "configure"
            system("dcop", "amarok", "playlist", "popupMessage", "This script does not require any configuration.<br /><br /><b>Version: #{@scriptversion}</b>")

        when "fetchLyrics"

            args = message.split()

            @artist = args[1]
            @title  = args[2]
            @album  = `dcop amarok player album`.chomp()

            if @artist == nil or @title == nil or @album == nil
                notFound()
            else
                fetchLyrics( @artist, @title, "" )
            end

        when "fetchLyricsByUrl"
            url = message.split()[1]

            fetchLyrics( "", "", url )
    end
end

